package com.jkt.rms.adapter;


import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import com.jkt.rms.commons.configuration.MessageSourceImpl;
import com.jkt.rms.commons.utils.RMSException;
import com.jkt.rms.commons.utils.ServiceLocator;

/**
 * This class provides implementation for Email related functionalities.
 * 
 * @author JKT
 * @version 0.1
 */
public class EmailAdaptor {

	
	private static final Logger	LOG	= Logger.getLogger(EmailAdaptor.class);
	private static MessageSourceImpl messagesourceimpl;
	
	
	/**
	 * This method send the mail 
	 * @param emailId
	 * @param subject
	 * @param message
	 * @return boolean
	 * @throws RMSException
	 */
	public static boolean sendEmail(String emailId, String subject,
	        String message)
	        throws RMSException {
		messagesourceimpl = ServiceLocator.getServiceLocator().locate("messageSourceImpl");
		//EMAIL.SERVER
		String strHost = messagesourceimpl.getMessage("email.server.name");
		//EMAIL.SENDER
		String strFromEmail =messagesourceimpl.getMessage("email.host.name");
		boolean status = true;
		try {
			Properties prop = System.getProperties();
			prop.put("mail.smtp.host", strHost);
			Session ses = Session.getDefaultInstance(prop, null);
			MimeMessage msg = new MimeMessage(ses);
			msg.setFrom(new InternetAddress(strFromEmail));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
			        emailId));
			msg.setSubject(subject);
			msg.setText(message);
			msg.setSentDate(new Date());
			Transport.send(msg);
		}
		catch (Exception e) {
			LOG.error("Exception occured in sendEmail():"+e.getCause());
			status = false;
			throw new RMSException("send.error.email","Error in sending mail");
		}
		return status;
		//Need to create emailAdapter DAO and insert it into EmailAudit Table 
		
	}
}